<template>
  <div>
    <!-- 轮播 -->
    <div class="banner">
        <div class="swiper-container" ref="swiper">
            <div class="swiper-wrapper">
                <div class="swiper-slide" v-for="(item,i) in bannerImg" :key="i">
                    <img :src="item.picurl" alt="">
                </div>
            </div>
            <!-- 分页器 -->
            <div class="swiper-pagination"></div>
        </div>
    </div>
</div>
</template>

<script>
// swiper@5 4和5版本好用
import Swiper from "swiper"
import 'swiper/css/swiper.css'
import {mapState} from 'vuex'
export default {
    name:'Banner',
    data() {
        return {
            
        }
    },
    async mounted(){
        // 这里使用async和await也是为了等待DOM更新，for循环结束之后，再去实例化swiper解决轮播图不能切换
        // 也可以使用watch和nextTick
        await this.getBannerImg()

        this.initSwiper()

        //  setTimeout(()=>{
        //     this.initSwiper()
        //  },1000)
    },
    computed:{
        ...mapState('home',['bannerImg']),
    },
    methods:{
        // swiper配置
        initSwiper(){
            var swiper = new Swiper(this.$refs.swiper, {
                loop:true,//无线循环
                slidesPerView:1.2,//一行显示1.2个
                centeredSlides:true,//居中显示
                autoplay:{
                    delay:2500,//2500毫秒自动切换
                    // disableOnInteraction:false,//用户操作过好，也自动播放
                },
                pagination: {//分页器
                el: ".swiper-pagination",
                clickable: true,
                },
            });
        },
        // 派发action 获取轮播图
        async getBannerImg(){
            await this.$store.dispatch('home/getBannerImg')
        },
    }
}
</script>

<style lang="less">
.banner{
    height: 5rem;
    background: white;
    .swiper-container{
        // 分页器小点选中的颜色
        --swiper-theme-color: #31C27C;
        padding-top: .2rem;
        padding-bottom: .25rem;
        width: 100%;
        height: 100%;
        .swiper-slide{
            img{
                width: 100%;
                height: 100%;
                transition: 0.4s;// 过渡
                transform: scale(0.9);//缩放
                border-radius: .15rem;
                box-shadow: 0 0.05rem 0.2rem rgba(0,0,0,0.25);
            }
            // 选中的图片样式
            &.swiper-slide-active{
                img{
                    transform: scale(1);//正常大小
                }
            }
        }    
    }
}
</style>